﻿using IdentityServer4.Models;
using IdentityServer4.Stores;
using Lk.Common.Helper;
using OAuth.Server.Domain;
using OAuth.Server.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OAuth.Server.OAuth
{
    public class ClientStore : IClientStore
    {
        private readonly ClientRepository _repository;

        public ClientStore(ClientRepository repository)
        {
            _repository = repository;
        }

        private async Task<ICollection<Secret>> FindSecrets(int clientId)
        {
            var models = await _repository.QuerySecrets(clientId);
            return models.Select(t => new Secret(t.Data, t.Title, t.ExpiredTime)).ToList();
        }

        public async Task<Client> FindClientByIdAsync(int clientId)
        {
            var model = await _repository.Queryclient(clientId);
            if (model == null) return null;
            var client = MapperHelper<TClient, Client>.Map(model);
            client.ClientSecrets = await FindSecrets(model.ClientId);
            var config = await _repository.QueryConfig(model.ClientId);
            if (config != null)
            {
                //client.AllowedCorsOrigins = JsonHelper.ToJson<string>(config.Origins ?? "[]").ToList();
                //client.AllowedGrantTypes = JsonHelper.JsonList<string>(config.Grants ?? "[]").ToList();
                //client.AllowedScopes = JsonHelper.JsonList<string>(config.Scopes ?? "[]").ToList();
                //client.IdentityProviderRestrictions = JsonHelper.JsonList<string>(config.Providers ?? "[]").ToList();
                //client.RedirectUris = JsonHelper.JsonList<string>(config.Uris ?? "[]").ToList();
                //client.PostLogoutRedirectUris = JsonHelper.JsonList<string>(config.LogoutUris ?? "[]").ToList();
            }

          //  client.Claims = await _repository.QueryClaims(model.Id);
         //   client.Properties = await _repository.QueryProperties(model.Id);
            return client;
        }

        Task<Client> IClientStore.FindClientByIdAsync(string clientId)
        {
            throw new NotImplementedException();
        }
    }
}
